#include "ProcessWin.h"


ProcessPtr ProcessWin::fromHandleAndName( const process_handle handle, const std::string& name_ )
{
	return ProcessPtr(new ProcessWin(handle, name_));
}

std::vector<ProcessModule>& ProcessWin::modules()
{
	if (!modules_loaded)
		fillModules();
	return modules_;
}

const process_handle ProcessWin::native() const
{
	return handle;
}

const std::string& ProcessWin::name() const
{
	return name_;
}

MemoryReader& ProcessWin::reader()
{
	return memreader;
}

ProcessWin::ProcessWin( const process_handle handle, const std::string& name_ ) : handle(handle), name_(name_), modules_loaded(false), memreader(handle)
{

}

void ProcessWin::fillModules()
{
	MODULEENTRY32 lpModuleEntry = {0};
	HANDLE hSnapShot = CreateToolhelp32Snapshot( TH32CS_SNAPMODULE, GetProcessIDbyProcessHandleZw(handle.get()) );

	if(!hSnapShot)
		return;

	lpModuleEntry.dwSize = sizeof(lpModuleEntry);
	BOOL bModule = Module32First( hSnapShot, &lpModuleEntry );

	while(bModule)
	{
		modules_.push_back(ProcessModule(lpModuleEntry.szModule,
			(address_t)lpModuleEntry.modBaseAddr, (address_t)lpModuleEntry.modBaseAddr + lpModuleEntry.modBaseSize));

		bModule = Module32Next( hSnapShot, &lpModuleEntry );
	}
	CloseHandle( hSnapShot );
}
